# -*- coding: utf-8 -*-
from django.shortcuts import render_to_response
from django.core.paginator import Paginator
from django.db import transaction
from django.template import RequestContext
from rest_framework import generics
from rest_framework.response import Response
from models import Book, LineItem
from cart import Cart
from serializers import LineItemSerializer
from forms import OrderForm
from django.contrib.auth.forms import UserCreationForm
from django.http import HttpResponseRedirect
from django.contrib.auth.decorators import login_required
from django.db.models import Q


def create_account(request):
    if request.method == 'POST':
        form = UserCreationForm(request.POST)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect("/bookstore/")
    else:
        form = UserCreationForm()
    return render_to_response('bookstoreapp/createaccount.html',
                              {'form': form},
                              context_instance=RequestContext(request))


def list_book(request):
    list_items = Book.objects.all()
    paginator = Paginator(list_items, 10)
    cart = request.session.get('cart', None)
    try:
        page = int(request.GET.get('page', '1'))
    except ValueError:
        page = 1

    try:
        list_items = paginator.page(page)
    except:
        list_items = paginator.page(paginator.num_pages)
    return render_to_response('bookstoreapp/list_book.html',
                              locals(),
                              context_instance=RequestContext(request))


def view_book(request, id):
    book_instance = Book.objects.get(id=id)
    return render_to_response('bookstoreapp/view_book.html', locals())


def view_cart(request):
    cart = request.session.get('cart', None)

    if not cart:
        cart = Cart()
        request.session['cart'] = cart
    return render_to_response('bookstoreapp/cart_view.html', locals())


def add_to_cart(request, id):
    book = Book.objects.get(id=id)
    cart = request.session.get('cart', None)
    if not cart:
        cart = Cart()
        request.session['cart'] = cart
    cart.add_book(book)
    request.session['cart'] = cart
    return view_cart(request)


def clean_cart(request):
    request.session['cart'] = Cart()
    return view_cart(request)


def search(request):
    list_items = []
    if 'q' in request.GET and request.GET['q']:
        q = request.GET['q']
        list_items = Book.objects.filter(Q(title__contains=str(q)) |
                                        (Q(ISBN=int(q) if q.isdigit() else 0)) |
                                        Q(authors__name__contains=str(q)))
    paginator = Paginator(list_items, 10)
    cart = request.session.get('cart', None)
    try:
        page = int(request.GET.get('page', '1'))
    except ValueError:
        page = 1
    try:
        list_items = paginator.page(page)
    except:
        list_items = paginator.page(paginator.num_pages)
    return render_to_response('bookstoreapp/list_book.html',
                              locals(),
                              context_instance=RequestContext(request))


@transaction.commit_on_success
@login_required(login_url='/bookstore/account/login/')
def create_order(request):
    form = OrderForm(request.POST or None)
    if form.is_valid():
        order = form.save()
        cart = request.session.get('cart', None)
        items = cart.items if cart else []
        for item in items:
            item.order = order
            item.save()
        clean_cart(request)
        return list_book(request)
    return render_to_response('bookstoreapp/create_order.html',
                              locals(),
                              context_instance=RequestContext(request))


class LineItemList(generics.ListCreateAPIView):
    model = LineItem
    serializer_class = LineItemSerializer

    def get(self, request, *args, **kwargs):
        cart = request.session.get('cart', None)
        items = cart.items if cart else []
        serializer = LineItemSerializer(items)
        return Response(serializer.data)

    def post(self, request, *args, **kwargs):
        if 'book' in request.POST:
            book = Book.objects.get(id=request.POST['book'])
            cart = request.session.get('cart', None)
            if not cart:
                cart = Cart()
                request.session['cart'] = cart
            cart.add_book(book)
            request.session['cart'] = cart
            serializer = LineItemSerializer(cart.items)
        else:
            serializer = LineItemSerializer([])
        return Response(serializer.data)
